package com.hf.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import com.base.bean.*;
import com.base.dao.*;
import com.base.service.*;
import com.hf.listener.MySessionContext;

import net.sf.json.JSONObject;
import tool.*;

/**
 * 1）注册的过程：
 * （user与openId建立对应关系的过程）
 * 
 * 录入用户名 密码
 * 前端传来的参数只需要code 与sessionId
 * openId有后端获取 然后拉取用户信息并存入数据库 
 * 
 * 2）登录的过程：
 * 通过openId来查看用户权限是否满足
 * 
 * code state 都是微信回调页面传递过来的参数
 * 参考：
 * http://www.cnblogs.com/jupal/articles/5132518.html
 * @author Administrator
 *
 */
public class LoginRegist extends BaseAction{
	private String code,accessToken,refreshToken,state;
	private String sessionId;
	private String username,psw;
	private String trueName,phone;
	private String nickname,headimg,company;
	
	private String provinceId,cityId,province,city;
	
	private UserService us;
	private HttpSession session;
	
	private List<MsessionBase> mssessions;
	private String json_msg;
	
	// 后面改到配置文件或数据库中(汇发机械)
	private static String appid="wxe09104e1398974e9";
	private static String secret="66c91360cc87bf8416ea3eb4913e760c";
		
	private static String url1="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
	private static String url2="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
	private static String url3="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENId&lang=zh_CN";
	
	

	/**主要是通过code获取openId 
	 * state='a'销售入口  'b'服务入口
	 * 
	 * 销售入口的URL如下：
	 * url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe09104e1398974e9&redirect_uri=http%3A%2F%2Fwe.51waji.com%2Fmicrohifo%2Flogin2&response_type=code&scope=snsapi_userinfo&state=a#wechat_red"
	 * 
	 */
	public String entrance(){
		String result="";
		JSONObject jsonObject=null;
		this.code=(this.code==null?"":this.code);
		this.state=(this.state==null?"":this.state);	//a:销售入口  b:服务入口
		this.openId=(this.openId==null?"":this.openId);
		this.refreshToken=(this.refreshToken==null?"":this.refreshToken);
		this.accessToken=(this.accessToken==null?"":this.accessToken);
		
		if(this.code.equals("")){
			this.tip="出现异常请重新由员工入口登录(code=001)";
			return ERROR;
		}
		
		if(!this.state.equals("init")){
			this.tip="员工入口出现异常，请联系管理员(code=002)"+this.state;
			return ERROR;
		}
		
		if(!this.code.equals("")){		// 没有refreshToken的情况下 通过code获取openId refreshToken
			result=this.getUrl(this.code,1);
			if(result==null){
				this.tip="页面失效，请重新由员工通道进入(code=003)";
				return ERROR;
			}
			
			try{
			jsonObject = JSONObject.fromObject(result);
			this.refreshToken=jsonObject.getString("refresh_token");
			this.accessToken=jsonObject.getString("access_token");
			this.openId=jsonObject.getString("openid");
			this.code="";		//code用过一次就没有用了 所以清空
			}catch(Exception e){
				this.tip="页面失效，请重新由员工通道进入(code=004)";
				return ERROR;
			}
			
			
		}
		
		
		if(this.openId.equals("")){
			this.tip="获取系统参数失败(code=005)";
			return ERROR;
		}
		
		
		
		// 验证openId是否是有效用户
		User user=UserService.getInstance().getByOpenId(this.openId);
		if(user==null){
			this.tip="为了能尽快通过审核，请务必填写真实信息！";
			return INPUT;
		}
		
		if(user.getUid()==-1){		//有可能是未获取到该用户
			this.tip="出现异常，请单击[员工通道]重新登录(code=006)";
			return INPUT;
		}
		
		if(user!=null && user.getState()==0){
			
			this.tip="还未通过审核，请耐心等待！或联系相关人员";
			this.nickname=user.getNickname();
			this.headimg=user.getHeadurl();
			this.city=user.getCity();
			this.province=user.getProvince();
			this.trueName=user.getTruename();
			this.company=user.getCompany();
			this.phone=user.getPhone();
//				
			
			return "check";
		}
		
		
		if(user.getState()>0){
			this.tip="欢迎您("+user.getNickname()+")";
			return SUCCESS;
		}else{
			this.tip="遇到异常，请联系管理员(code=007)";
			return ERROR;
		}
		
	}
	
	
	/**
	 * 登录过程为：
	 * 获取openId 然后在jsp端将session与openId建立关联关系
	 * 
	 * @return
	 */
	public String login(){
		
		this.openId=(this.openId==null?"":this.openId);
		this.refreshToken=(this.refreshToken==null?"":this.refreshToken);
		this.state=(this.state==null?"":this.state);	//a:销售入口  b:服务入口
		this.accessToken=(this.accessToken==null?"":this.accessToken);
		
		if(!this.state.equals("a")){
			this.tip="销售员入口系统错误，请联系管理员(code=100)";
			return ERROR;
		}
		if(this.openId.equals("")){
			this.tip="如果重试后仍然遇到此错误，请联系管理员(code=101)";
			return ERROR;
		}
		
		
		User u=null;
		try{
		u=UserService.getInstance().getByOpenId(this.openId);
		if(u==null){
			this.tip="该用户没有注册";
			return INPUT;
		}
		if(u.getState()==2){
			this.tip="该用户已经离职";
			return ERROR;
		}
		}catch(Exception e){
			this.tip="出现异常(code=102)";
			return ERROR;
		}
		
		// 如果session没有保存user 则保存
		HttpSession session=MySessionContext.getSession(this.openId);
		Integer count=MySessionContext.getSessionCounts();
		count=(count==null?0:count);
		
		//u肯定不为空
		if(session!=null){
			this.tip="您好"+u.getNickname()+"(用户"+count+"人)";
		}else{
			count=count+1;
			this.tip="您好"+u.getNickname()+"(用户"+count+"人)";
		}

//		// 获取消息
//		this.mssessions = this.getMsg(u.getUid(),1);
//		try {
//			this.json_msg =  JsonTool.obj2json(this.mssessions);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			this.json_msg=null;
//		}
		
		return SUCCESS;
		

		
	}
	
//	private List<MsessionBase> getMsg(Integer uid,Integer state){
//		return  MsessionService.getInstance().getListByUser(uid, state);
//	}
		
	/**
	 * 注册过程：
	 * openId nickname sex headimgurl truename checked 
	 * @return
	 */
	public String regist(){	
		User user=null;
		this.openId=(this.openId==null?"":this.openId);
		
		if(this.openId.equals("")){
			this.tip="未识别到用户，请重新由[员工通道]登录";
			return ERROR;
		}
		
		try{
		User u=UserService.getInstance().getByOpenId(this.openId);
		if(u.getState()==0){	//不会到达这个条件 因为注册成功后再次登录 在入口就跳转了
			this.tip="还未通过审核，请耐心等待！或联系相关人员";
			return ERROR;	
		}else if(u.getState()==1){
			this.tip="您已经通过审核，请重新登录";
			return ERROR;
		}
		}catch(Exception e){
			//System.out.println("can't find the user by openId");
			e.printStackTrace();
		}
		
		
		
		this.accessToken=(this.accessToken==null?"":this.accessToken);
		if(this.openId.equals("") || this.accessToken.equals("")){
			this.tip="无法拉取用户信息，重试仍显示此错误，请联系管理员（openId or accessToken is not exit）";
			return ERROR;
		}	
		
		this.phone = (this.phone == null ? "" : this.phone.replaceAll("\\s*", ""));
		this.trueName = (this.trueName == null ? "" : this.trueName.replaceAll("\\s*", ""));
		this.company = (this.company == null ? "" : this.company.replaceAll("\\s*", ""));
		
		this.provinceId=(this.provinceId==null?"0":this.provinceId);
		this.cityId=(this.cityId==null?"0":this.cityId);
		
		if(this.company.equals("") || this.phone.equals("") || this.trueName.equals("")){
			this.tip="请完善基本信息（姓名|电话|公司名）";
			return INPUT;
		}
		
		if(this.provinceId.equals("0") || this.cityId.equals("0")){
			this.tip="请选择单位所在省市";
			return INPUT;
		}
		
		try {
			if(!ClientTool.isMobileNO(this.phone) || ClientTool.isName(this.trueName) > 0){
				this.tip="请检查电话或姓名的格式";
				return ERROR;
			}
		} catch (Exception e) {
			this.tip="验证姓名时出现异常，请联系管理员";
			return ERROR;
		}
		
		user=this.pullUserInfo(this.accessToken,this.openId);		//拉去用户信息
		if(user==null){
			this.tip="拉取用户信息失败，若反复出现此情况请联系管理员";
			return ERROR;
		}
		
		AddressService as = AddressService.getInstance();
		this.cityId=(this.cityId==null?"0":this.cityId);
		this.provinceId=(this.provinceId==null?"0":this.provinceId);
		this.province=(this.province==null?"":this.province);
		this.city=(this.city==null?"":this.city);
		
		if(!this.provinceId.equals("0"))
			this.province=as.getNameByCode(AddressService.ADD_TYPE.PROVINCE, this.provinceId);
		if(!this.cityId.equals("0"))
			this.city=as.getNameByCode(AddressService.ADD_TYPE.CITY, this.cityId);
		
		
		
		
		this.nickname=user.getNickname();
		this.headimg=user.getHeadurl();		
//		user.setNickname(this.nickname);
//		user.setHeadurl(this.headimg);
//		user.setOpenid(this.openId);
		user.setName(this.nickname);
		user.setTruename(this.trueName);
		user.setCompany(this.company);
		user.setPhone(this.phone);
		user.setCity(this.city);
		user.setCityId(this.cityId);
		user.setProvince(this.province);
		user.setProvinceId(this.provinceId);
		user.setState(0);	//初始状态
		
		us=UserService.getInstance();
		
		//User u2=us.getByOpenId(this.openId);
		
		
		boolean isAdd=us.getUserDao().merge(user);
		if(!isAdd){
			this.tip="提交新注册用户失败！";
			return ERROR;
			
		}
		this.tip="注册成功,请等待管理员审核！";
		return SUCCESS;
		
		
	}


	/**
	 * type:1 通过code换取
	 * 2：通过REFRESH_TOKEN换取
	 */
	private String getUrl(String code,int type){	//注意getopenId在父类中已经有了 
		String url="";
		if(type==1){
			url=this.url1;
			url=url.replace("SECRET",this.secret);
			url=url.replace("CODE",code);
			url=url.replace("APPID",this.appid);
			this.code="";
		}
		else if(type==2){
			url=this.url2;
			url=url.replace("REFRESH_TOKEN",code);
			url=url.replace("APPID",this.appid);	
		}	
		
		return WechatTool.readUrl(url);
		

	}
	
	
	// 拉取用户信息
	private User pullUserInfo(String accessToken,String openId){
		User user=new User();
		String url=this.url3;
		url=url.replace("ACCESS_TOKEN",accessToken);
		url=url.replace("OPENID",openId);
		String result="";
	try{
		result=WechatTool.readUrl(url);
		JSONObject jsonObject = JSONObject.fromObject(result);
		user.setOpenid(openId);
		user.setNickname(jsonObject.getString("nickname"));
		user.setHeadurl(jsonObject.getString("headimgurl"));
	}catch(Exception e){
		return null;
	}
	return user;

	}
	
	
	
	
	
	@Override
	public String execute() {
		this.code=(code==null?"":code);
		
		
		// TODO Auto-generated method stub
		return null;
	}
	
	//test
	public static void main(String[] args){
		LoginRegist g=new LoginRegist();
		
		UserService us=UserService.getInstance();
		UserDao ud = us.getUserDao();
		User u=new User();
		u.setName("name");
		u.setOpenid("openid");
		ud.merge(u);
	
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getSessionId() {
		return sessionId;
	}

	public void setSessionId(String sessionId) {
		this.sessionId = sessionId;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPsw() {
		return psw;
	}

	public void setPsw(String psw) {
		this.psw = psw;
	}

	public String getTrueName() {
		return trueName;
	}

	public void setTrueName(String trueName) {
		this.trueName = trueName;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}



	public String getAccessToken() {
		return accessToken;
	}

	public void setAccessToken(String accessToken) {
		this.accessToken = accessToken;
	}

	public String getRefreshToken() {
		return refreshToken;
	}

	public void setRefreshToken(String refreshToken) {
		this.refreshToken = refreshToken;
	}

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getHeadimg() {
		return headimg;
	}

	public void setHeadimg(String headimg) {
		this.headimg = headimg;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getCompany() {
		return company;
	}

	public void setCompany(String company) {
		this.company = company;
	}


	public String getProvinceId() {
		return provinceId;
	}


	public void setProvinceId(String provinceId) {
		this.provinceId = provinceId;
	}


	public String getCityId() {
		return cityId;
	}


	public void setCityId(String cityId) {
		this.cityId = cityId;
	}


	public String getProvince() {
		return province;
	}


	public void setProvince(String province) {
		this.province = province;
	}


	public String getCity() {
		return city;
	}


	public void setCity(String city) {
		this.city = city;
	}


	public List<MsessionBase> getMssessions() {
		return mssessions;
	}


	public void setMssessions(List<MsessionBase> mssessions) {
		this.mssessions = mssessions;
	}


	public String getJson_msg() {
		return json_msg;
	}


	public void setJson_msg(String json_msg) {
		this.json_msg = json_msg;
	}
	
}
